package event

import (
	"github.com/beego/beego/v2/server/web/context"
	"strings"
	"sync"
)

type Handler func(v interface{}, ctx *context.Context)

type BusToOne map[string]Handler
type BusToMany map[string][]Handler

var B2O map[string]Handler
var B2M map[string][]Handler

func init() {
	B2O = make(map[string]Handler)
	B2M = make(map[string][]Handler)
}

func Listen(name string, handler Handler) {
	B2O[name] = handler
}
func DispatchToOne(name string, data interface{}, ctx *context.Context) {
	handler, ok := B2O[name]
	if ok {
		handler(data, ctx)
	}
}

func ListenJoin(name string, handler Handler) {
	eventNames := strings.Split(name, " ")
	for _, eventName := range eventNames {
		B2M[eventName] = append(B2M[eventName], handler)
	}
}
func DispatchToManySync(name string, data interface{}, ctx *context.Context) {
	handlers, ok := B2M[name]
	if ok {
		for _, handler := range handlers {
			handler(data, ctx)
		}
	}
}

func DispatchToMany(name string, data interface{}, ctx *context.Context) {
	handlers, ok := B2M[name]
	if ok {
		var wg sync.WaitGroup
		wg.Add(len(handlers))
		for _, handler := range handlers {
			go func(handler2 Handler) {
				handler2(data, ctx)
				wg.Done()
			}(handler)
		}
		wg.Wait()
	}
}

//下面是一些打架习惯使用的名称的别名方法
var On = ListenJoin
var OnOne = Listen
var Trigger = DispatchToMany
var TriggerSync = DispatchToManySync

type AuthEvent struct {
	Name    string
	Access  bool
	Message string
}
